(function () {

    var x;
    var $accoutG;
    var $contact;
    var userInfo;

    function onInit() {
        onInitData();
        onShowUserInfoSafe();
        onStartCamera();
    }

    function onInitData() {
        app.setViewBackText("设置");
        $accoutG = x.$view.find('.safe .account-g');
        $contact = x.$view.find('.safe .contact');
    }

    /**
     * 获取用户信息
     */
    function onShowUserInfoSafe() {
        var userId = backService.localLoginInfo.id;
        backService.setting.onShowUserInfoSafe(userId, function (json) {
            var data = json.data;
            userInfo = data;
            onSetUserInfoSafe(data);
        }, function (e) {
            app.showToast(e.msg);
        });
    }

    /**
     * 设置用户信息
     */
    function onSetUserInfoSafe(data) {
        var avatar = data.avatar;
        if (avatar) {
            var src = backService.getFileUrl(avatar);
            $accoutG.find('li.avatar img').attr("src", src);
        }else{
            $accoutG.find('li.avatar img').attr("src", "img/message/index/head.jpg");
        }
        $accoutG.find('.nickname .title').text(data.nickName);
        $accoutG.find('.account .title').text(null);
        $contact.find('.phone .title').text(data.mobile);
        $contact.find('.email .title').text(data.email);
    }

    /**
     * 启动相机或相册
     */
    function onStartCamera() {
        $accoutG.find('.avatar').on("click", "a", function () {
            var options = null;
            app.showPopupMenu("", ['选择相机', '打开相册'], function (index) {
                if (index == 0) {// 拍照
                    options = setOptions(Camera.PictureSourceType.CAMERA);
                } else {// 相册
                    options = setOptions(Camera.PictureSourceType.SAVEDPHOTOALBUM)
                }
                navigator.camera.getPicture(cameraSuccess, cameraError, options);

            });
        });
    }

    /**
     * 调用成功
     */
    function cameraSuccess(imageData) {
        console.log(imageData);
        getFileEntry(imageData);
        $accoutG.find('.avatar img').attr("src",imageData);
    }

    /**
     * 调用失败
     */
    function cameraError(message) {
        console.log(message)
    }

    // 获取fileEntry
    function getFileEntry(imgUri) {
        window.resolveLocalFileSystemURL(imgUri, function success(fileEntry) {

            updateAvatarImgFile(fileEntry)
        }, function () {
            // 以上方法获取失败，再调用createNewFileEntry
            createNewFileEntry(imgUri);
        });
    }

    function createNewFileEntry(imgUri) {
        window.resolveLocalFileSystemURL(cordova.file.cacheDirectory, function success(dirEntry) {

            // 获取fileEntry
            dirEntry.getFile(imgUri, {create: true, exclusive: false}, function (fileEntry) {

                updateAvatarImgFile(fileEntry)
            }, function (e) {
                console.log(e)
            });

        }, function (e) {
            console.log(e)
        });
    }

    function updateAvatarImgFile(fileEntry) {
        // !! Assumes variable fileURL contains a valid URL to a text file on the device,
        var fileURL = fileEntry.toURL();

        var success = function (r) {
            console.log("成功上传...");
            console.log("Code = " + r.responseCode);
            /*ios才支持*/
            navigator.camera.cleanup(onClearSuccess, onClearFail);
        };

        var fail = function (error) {
            alert("An error has occurred: Code = " + error.code);
        };

        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
        options.mimeType = "image/jpeg";

        var params = {};
        params.userId = userInfo.id;
        params.avatar = userInfo.avatar;

        options.params = params;

        var ft = new FileTransfer();
        var url = backService.baseUrl+"/setting/on_update_avatar_file.json";
        ft.upload(fileURL, encodeURI(url), success, fail, options);
    }

    
    function onClearSuccess() {
        console.log("清除成功!");
    }

    function onClearFail(message) {
        console.log("清除失败!"+message );
    }
    /**
     * 配置参数，选择使用相机还是相册
     * @param srcType
     * @returns {{quality: number, destinationType: *, sourceType: *, allowEdit: boolean, mediaType: *, encodingType: *, targetWidth: number, targetHeight: number}}
     */
    function setOptions(srcType) {
        var cameraOptions = {
            quality: 99,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: srcType,
            allowEdit: false,
            mediaType: Camera.MediaType.PICTURE,
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 100,
            targetHeight: 100
        };
        return cameraOptions;
    }


    window.onViewInit_setting_safe = function (view) {
        x = view.context;
        onInit();
    }
})();